<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <lay-button type="normal" @click="search" size="sm">
          <i class="layui-icon layui-icon-refresh-three marginR5"></i>刷新
        </lay-button>
        <download-excel class="hide-on-phone marginL15" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <lay-button size="sm" type="danger">
            <i class="layui-icon layui-icon-export marginR5"></i>导出 Excel
          </lay-button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db ref="udb" :collection="collectionList" :where="where" page-data="replace"
        field="create_date,wallet_type,trade_type,trade_id,change_before_amount,changet_after_amount,commission_percentage,change_amount,real_get_amount,remark"
        :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
        v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual" @load="onqueryload">
        <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe @selection-change="selectionChange">
          <uni-tr>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.wallet_type_localdata" @filter-change="filterChange($event, 'wallet_type')">钱包类型</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.trade_type_localdata" @filter-change="filterChange($event, 'trade_type')">交易类型</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'trade_id')" sortable @sort-change="sortChange($event, 'trade_id')">流水单号</uni-th>
            <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'change_before_amount')" sortable @sort-change="sortChange($event, 'change_before_amount')">变动前金额</uni-th>
            <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'changet_after_amount')" sortable @sort-change="sortChange($event, 'changet_after_amount')">变动后金额</uni-th>
            <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'commission_percentage')" sortable @sort-change="sortChange($event, 'commission_percentage')">平台抽成</uni-th>
            <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'change_amount')" sortable @sort-change="sortChange($event, 'change_amount')">变动金额</uni-th>
            <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'real_get_amount')" sortable @sort-change="sortChange($event, 'real_get_amount')">实际金额</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'remark')" sortable @sort-change="sortChange($event, 'remark')">备注</uni-th>
            <uni-th align="center">生成时间</uni-th>
            <!-- <uni-th align="center">操作</uni-th> -->
          </uni-tr>
          <uni-tr v-for="(item,index) in data" :key="index">
            <uni-td align="center">
              <div
                :style="toggleModule.wallet_type[item.wallet_type].style"
              >{{options.wallet_type_valuetotext[item.wallet_type]}}</div>
            </uni-td>
            <uni-td align="center">{{options.trade_type_valuetotext[item.trade_type]}}</uni-td>
            <uni-td align="center">{{item.trade_id}}</uni-td>
            <uni-td align="center">
              <div>
                {{ +BigJs(item.change_before_amount).div(100) }}元
              </div>
            </uni-td>
            <uni-td align="center">
              <div>
                {{ +BigJs(item.changet_after_amount).div(100) }}元
              </div>
            </uni-td>
            <uni-td align="center">
              <div v-if="item.commission_percentage">
                  {{ +BigJs(item.commission_percentage).div(1000).times(100) }}%
              </div>
            </uni-td>
            <uni-td align="center">
              <div class="flexStyle" :style="toggleModule.trade_type[item.trade_type].style">
                <div v-if="item.trade_type==0||item.trade_type==3">+</div>
                <div v-else>-</div>
                <div>{{ +BigJs(item.change_amount).div(100) }}元</div>
              </div>
            </uni-td>
            <uni-td align="center">
              <div class="flexStyle" :style="toggleModule.trade_type[item.trade_type].style">
                <div v-if="item.trade_type==0||item.trade_type==3">+</div>
                <div v-else>-</div>
                  <div>
                    {{ +BigJs(item.real_get_amount).div(100) }}元
                  </div>
              </div>
            </uni-td>
            <uni-td align="center">
              <lay-tooltip v-if="item.remark.length>20" :content="item.remark" :isDark="false">
                <div class="flexStyle">{{item.remark.substr(0,20)+' ...'}}</div>
              </lay-tooltip>
            <div v-else>{{item.remark}}</div>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :date="item.create_date" :threshold="[0,0]"></uni-dateformat>
            </uni-td>
            <!-- <uni-td align="center">
              <view class="uni-group">
                <button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini" type="primary">修改</button>
                <button @click="confirmDelete(item._id)" class="uni-button" size="mini" type="warn">删除</button>
              </view>
            </uni-td> -->
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/food-merchant-bill.js';
  import {toggleModule} from './style.js';
  import BigJs from 'big.js'
  import moment from 'moment'
  import {store} from '@/uni_modules/uni-id-pages/common/store.js'

  const db = uniCloud.database()
  // 表查询配置
  const dbOrderBy = 'create_date desc' // 排序字段
  const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

  export default {
    data() {
      return {
        toggleModule,


        collectionList: `food-merchant-bill`,
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            "wallet_type_localdata": [
              {
                "value": 0,
                "text": "冻结金额"
              },
              {
                "value": 1,
                "text": "可用金额"
              }
            ],
            "trade_type_localdata": [
              {
                "value": 0,
                "text": "收入"
              },
              {
                "value": 1,
                "text": "提现"
              },
              {
                "value": 2,
                "text": "扣款"
              },
              {
                "value": 3,
                "text": "充值"
              },
              {
                "value": 4,
                "text": "划转"
              }
            ]
          },
          ...enumConverter
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "food-merchant-bill.xls",
          "type": "xls",
          "fields": {
            "所属商户": "merchant_id",
            "所属用户": "user_id",
            "钱包类型": "wallet_type",
            "交易类型": "trade_type",
            "流水单号": "trade_id",
            "变动前金额": "change_before_amount",
            "变动后金额": "changet_after_amount",
            "平台抽成": "commission_percentage",
            "变动金额": "change_amount",
            "实际获得": "real_get_amount",
            "抽成金额": "commission_amount",
            "备注": "remark"
          }
        },
        exportExcelData: []
      }
    },
    onLoad() {
      this._filter = {}
    },
    onReady() {
      this.search();
    },
    methods: {
      getBaseWhere(params){
        if(store.userInfo&&store.userInfo.merchant_id){
            if(typeof params === 'string'){
              params+=`merchant_id=="${store.userInfo.merchant_id}"`
            }else{
              params.merchant_id=store.userInfo.merchant_id
            }
        }
        return params
      },
      getMoment(date){
        return moment(date).format(`YYYY-MM-DD HH:mm:ss`)
      },
      BigJs(args){
        return new BigJs(args)
      },


      
      onqueryload(data) {
        this.exportExcelData = data
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        const newWhere = this.getWhere()
        this.where = this.getBaseWhere(newWhere)
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      // 多选处理
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      // 批量删除
      delTable() {
        this.$refs.udb.remove(this.selectedItems(), {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        this.$refs.udb.remove(id, {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        if (Object.keys(newWhere).length) {
          this.where = this.getBaseWhere(newWhere)
        } else {
          this.where = this.getBaseWhere(``)
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      }
    }
  }
</script>

<style>
</style>
